package cn.lzx.service.impl;

import cn.lzx.domain.PurchaseApply;
import cn.lzx.exception.GlobalCustomException;
import cn.lzx.feign.ProductService;
import cn.lzx.domain.Product;
import cn.lzx.domain.Stock;

import cn.lzx.domain.StockWarningLog;
import cn.lzx.dto.StockDto;
import cn.lzx.exception.GlobalErrorCode;
import cn.lzx.feign.PurchaseApplyService;
import cn.lzx.mapper.StockMapper;
import cn.lzx.properties.StockThresholdProperties;
import cn.lzx.result.JSONResult;
import cn.lzx.service.IStockService;
import cn.lzx.service.IStockWarningLogService;
import cn.lzx.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author star
 * @since 2022-09-29
 */
@Service
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock> implements IStockService {

    @Autowired
    private ProductService productService;

    @Autowired
    private IStockWarningLogService stockWarningLogService;

    @Autowired
    private PurchaseApplyService purchaseApplyService;

    @Autowired
    private StockThresholdProperties stockThresholdProperties;

    @Override
    public void iao(StockDto stockDto) {
        //根据状态判断出入库 0，入库   1，出库
        Stock stock = selectStock(stockDto.getProductId());
        if(stockDto.getStatus() == 0){// 入库
            if (stock == null){//如果仓库没有，就新增商品
                stock = new Stock();
                BeanUtils.copyProperties(stockDto,stock);

                //调用feign接口，查询到product
                JSONResult jsonResult = productService.get(stockDto.getProductId());
                //断言jsonresult
                AssertUtil.isTrue(jsonResult.isSuccess(),GlobalErrorCode.QUERY_FAILED);
                //data 为product数据
                Object data = jsonResult.getData();
                AssertUtil.isNotNull(data,GlobalErrorCode.PARAM_IS_NULL_ERROR);
                String s = JSONObject.toJSONString(data);
                Product product = JSON.parseObject(s, Product.class);
                stock.setProductName(product.getProductName());
                stock.setCreateTime(new Date());
                insert(stock);

            }else { //stock != null ,就修改数量
                stock.setCount(stockDto.getCount());
                updateById(stock);
            }
            /*出库需要完成库存判断，库存少于阈值时，
            记录库存警告日志，阈值使用yml进行常量设置，
            并调用采购服务进行采购申请-20<br/>
            * */
        }else {//出库

            //库存的数量
            Integer count = stock.getCount();
            //判断存库数量是否小于出库数量
            if (count < stockDto.getCount()){//库存不足
                //在判断是否库存少于阈值
                if (count < stockThresholdProperties.getThreshold()){

                    StockWarningLog stockWarningLog = new StockWarningLog();
                    //记录库存警告日志
                    BeanUtils.copyProperties(stock,stockWarningLog);
                    stockWarningLog.setCreateTime(new Date());
                    stockWarningLog.setInfo(stock.getProductName()+"库存不足");
                    //保存警告日志
                    stockWarningLogService.insert(stockWarningLog);
                    //调用采购服务进行采购申请
                    PurchaseApply purchaseApply = new PurchaseApply();
                    BeanUtils.copyProperties(stock,purchaseApply);
                    purchaseApply.setCreateTime(new Date());
                    purchaseApply.setStatus(0);
                    purchaseApply.setCount(100);
                    purchaseApplyService.saveOrUpdate(purchaseApply);
                    throw new GlobalCustomException("出库失败，库存少于阈值时");

                }

            }else {//库存充足
                //修改库存数量
                stock.setCount(stock.getCount()-stockDto.getCount());
                updateById(stock);
                PurchaseApply purchaseApply = new PurchaseApply();
                BeanUtils.copyProperties(stock,purchaseApply);
                purchaseApply.setCreateTime(new Date());
                purchaseApply.setStatus(0);
                purchaseApply.setCount(100);
                purchaseApplyService.saveOrUpdate(purchaseApply);
                throw new GlobalCustomException("出库失败,库存充足时");

            }


        }
    }

    @Override
    public List<Stock> lak() {
        // 1.获取库存阈值
        Integer threshold = stockThresholdProperties.getThreshold();
        Wrapper<Stock> wrapper = new EntityWrapper<>();
        wrapper.lt("count", threshold);
        List<Stock> stocks = selectList(wrapper);
        return stocks;
    }


    //获取Stock
    private Stock selectStock(Long productId) {

        Wrapper<Stock> wrapper = new EntityWrapper<>();

        wrapper.eq("product_id", productId);

        return selectOne(wrapper);

    }
}
